﻿using System;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace RGB.SharePoint.SPEasyCopy
{
    public partial class CopyOrMoveItem : LayoutsPageBase
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate() 
            {
                SPWeb web = SPContext.Current.Web;
                using (SPSite newSite = new SPSite(web.Url))
                {
                    using (SPWeb newWeb = newSite.OpenWeb())
                    {
                        string baseURL = newWeb.Url.ToString();
                        string listId = Page.Request.QueryString["List"];
                        string itemId = Page.Request.QueryString["ID"];
                        string action = Page.Request.QueryString["Action"];
                        try
                        {
                            if (!Page.IsPostBack)
                            {
                                if (string.IsNullOrEmpty(listId) || string.IsNullOrEmpty(itemId))
                                {
                                    throw new Exception("No Document Library/Item selected.");
                                }
                                SPDocumentLibrary doclib = (SPDocumentLibrary)newWeb.Lists[new System.Guid(listId)];                               
                                SPListItem item = doclib.Items.GetItemById(int.Parse(itemId));
                                SPFolder root = doclib.RootFolder;
                                if (doclib.DoesUserHavePermissions(web.CurrentUser, SPBasePermissions.AddListItems))
                                {
                                    TreeNode node = new TreeNode();
                                    node = Utility.GetFolderNode(node, root, baseURL, web.CurrentUser);
                                    node.Text = doclib.Title;
                                    node.NavigateUrl = "javascript:void(0)";
                                    node.ToolTip = baseURL + "/" + root.Url;
                                    node.ImageUrl = baseURL + "/_layouts/images/folder.gif";
                                    FolderTreeView.Nodes.Add(node);
                                    FolderTreeView.DataBind();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageLabel.ForeColor = Color.Red;
                            MessageLabel.Text = "Error: " + ex.Message;
                        }
                    }
                }
            });
        }

        protected void OkButton_Click(object sender, EventArgs e)
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                string listId = Page.Request.QueryString["List"];
                string itemId = Page.Request.QueryString["ID"];
                string action = Page.Request.QueryString["Action"];

                string selectedFolderPath = FolderTreeView.SelectedNode.ToolTip;
                if (!string.IsNullOrEmpty(selectedFolderPath))
                {
                    SPDocumentLibrary doclib = (SPDocumentLibrary)web.Lists[new System.Guid(listId)];
                    SPListItem item = doclib.Items.GetItemById(int.Parse(itemId));
                    string filePath = selectedFolderPath + "/" + item.File.Name;
                    SPFile file = web.GetFile(filePath);
                    string correctedPath = filePath;
                    while (file.Exists)
                    {
                        correctedPath = selectedFolderPath + "/Copy of " + item.File.Name;
                        file = web.GetFile(correctedPath);
                    }
                    if (action == "CopyTo")
                    {
                        item.CopyTo(correctedPath);
                    }
                    if (action == "MoveTo")
                    {
                        item.File.MoveTo(correctedPath);
                    }
                    HttpContext context = HttpContext.Current;
                    if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
                    {
                        context.Response.Write("<script type='text/javascript'>alert('Operation Completed Successfully.');</script>");
                        context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                        context.Response.Flush();
                        context.Response.End();
                    }
                }
                else
                {
                    MessageLabel.ForeColor = System.Drawing.Color.Red;
                    MessageLabel.Text = "Please select folder first.";
                }
            }
            catch (Exception ex)
            {
                MessageLabel.ForeColor = Color.Red;
                MessageLabel.Text = "Error: " + ex.Message;
            }            
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                context.Response.Flush();
                context.Response.End();
            }
        }
    }
}
